//客户服务器
var ROOTHTTP = 'http://api.zetikeji.com/api/';
var ROOTIMAGE = '';
var HTTP_DOMAIN = "http://zetikeji.com/";
var IMAGE_HTTP = "https://oss.zetikeji.com";
//公司服务器
//var ROOTHTTP = '';
//var ROOTIMAGE = '';

function notice() {
	api.openWin({
		name: "none_win",
		url: "none_win.html"
	})
}
// 拨打客服电话
function kefu_call() {
	api.call({
		type: 'tel_prompt',
		number: '4000211567'
	});
}

//需要登录后才能访问的页面数组
var arr_login_win = ['fuzhen_win', 'chat_win', 'tuisong_xiaoxi_win', 'wenzhen_order_win', 'chufang_order_win', 'my_doctor_win', 'voucher_center_win', 'phone_num_win', 'shouhuodizhi_win', 'yu_e_win', 'jifen_win', 'my_record_win', 'my_paifang_win']
//常用正则表达式
var REG_TELEPHONE = /^1[34578]\d{9}$/;
var REG_VERIFY = /^\d{4}$/;
var REG_PWD = /^\w{6,12}$/;
var REG_CASH = /^\d{1,5}(\.[0-9]{1,2})?$/;
var REG_CARDNO = /^(\d{16})|(\d{19})$/;
var REG_CHANA = /^[\u4E00-\u9FA5]{2,8}$/;
var REG_BANK = /^.{2,40}$/;
var REG_APPLYNAME = /^.{1,10}$/;
var REG_CARCOLOR = /^.{1,6}$/;
//汽车牌照号
var REG_CARNO = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[警京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
var REG_BLANK = /^\s*$/; //空字符串
//初始化界面
function hb_ready() {
	//开启沉静式
	hb_fix_header();
	//初始化返回按钮
	hb_init_back_btn();
	//初始化点击链接打开页面功能
	hb_init_openwinby_click();
	//设置状态栏样式
	api.setStatusBarStyle({
		style: 'dark'
	});
}
//开启沉静式
function hb_fix_header() {
	var header = $api.dom('.hd');
	var title = $('.aui-title');
	if (header) {
		$api.fixStatusBar(header);
	}
	if (title && api.pageParam.title) {
		title.html(api.pageParam.title);
	}
}
//初始化返回按钮
function hb_init_back_btn() {
	var back = $('#back');
	if (back) {
		back.on('click', function () {
			api.closeWin();
		});
	}
}
//初始化点击链接打开页面功能
function hb_init_openwinby_click() {
	var isContain = false,
		btns, tourl, title, index, intro, address, tel, pic, id, empid, mytitle;
	//1、找出所有的需要打开win的链接
	if (!(btns = $('.openwin'))) {
		return;
	} //如果没有需要打开的页面就返回
	//2、遍历所有需要打开的win,解绑on 的click事件
	for (var i = 0; i < btns.length; i++) {
		$(btns[i]).off('click');
	}

	//3、然后再添加click事件，遍历所有需要打开的win,获取标题title,跳转地址tourl,页面参数p_*
	for (var i = 0; i < btns.length; i++) {
		//添加点击事件
		$(btns[i]).on('click', function (e) {

			//阻止冒泡事件
			event.stopPropagation();
			tourl = $(this).data('win');
			title = $(this).data('title'); //页面标题
			index = $(this).data('index'); //订单页面的序号
			id = $(this).data('id');
			content = $(this).data('content');


			content2 = $(this).data('content2');
			content3 = $(this).data('content3');
			content4 = $(this).data('content4');


			var ppm = {
				title: title,
				index: index,
				id: id,
				content: content,
				content2: content2,
				content3: content3,
				content4: content4
			};

			//3、循环遍历arr_login_win数组，检查是否有被拦截的页面
			for (var i = 0; i < arr_login_win.length; i++) {
				if (tourl == arr_login_win[i]) {
					isContain = true;
					break;
				}
			}

			if (isContain) { //如果是被拦截的页面
				isContain = false;
				if ($api.getStorage('emp')) {
					//4、打开win页面
					api.openWin({
						name: tourl,
						url: tourl + '.html',
						pageParam: ppm,
						animation: {
							type: 'movein',
							subType: 'from_right',
							duration: 300
						},
						slidBackEnabled: false
					});
				} else {
					api.confirm({
						title: '您需要先登录哦！',
						msg: '点击确认跳到登录页面',
						buttons: ['先逛逛', '确定']
					}, function (ret, err) {
						var index = ret.buttonIndex;
						if (index == 2) { //确认跳转登录页面
							api.openWin({
								name: 'login',
								url: 'widget://html/login.html',
								slidBackEnabled: false,
								reload: true
							});
						}
					});
				}
			} else {
				//4、打开win页面
				api.openWin({
					name: tourl,
					url: tourl + '.html',
					pageParam: ppm,
					animation: {
						type: 'movein',
						subType: 'from_right',
						duration: 300
					}

				});
			}





		})


	}
}
//检查用户是否登录
function hb_check_login() {
	if ($api.getStorage('emp').userId) {
		//alert('存在：' + JSON.stringify($api.getStorage('emp').userId));
		return true;
	} else {
		//	alert('不存在：' + JSON.stringify($api.getStorage('emp').userId));
		var dialog = new auiDialog({});
		dialog.alert({
			title: '您需要先登录哦！',
			msg: '点击确认跳到登录页面',
			buttons: ['先逛逛', '确定']
		}, function (ret) {
			// alert(ret.buttonIndex);
			if (buttonIndex == 2) { //确认跳转登录页面

			}
		});
	}
}

//打开一个frame
function hb_openframeby_auto(name, ppm) {
	var hh = $('header')[0] ? $('header').offset().height : 0,
		fh = $('footer')[0] ? $('footer').offset().height : 0;
	api.openFrame({
		name: name,
		url: name + '.html',
		pageParam: ppm,
		rect: {
			x: 0,
			y: hh,
			w: api.winWidth,
			h: api.winHeight - hh - fh

		}
	});
}

//在一个标签容器中打开一个frame
function hb_openframeby_tag(tagid, name, ppm) {
	var hh = $(tagid)[0] ? $(tagid).offset().top : 0,
		fh = $('footer')[0] ? $('footer').offset().height : 0;
	api.openFrame({
		name: name,
		url: name + '.html',
		pageParam: ppm,
		rect: {
			x: 0,
			y: hh,
			w: api.winWidth,
			h: api.winHeight - hh - fh

		}
	});
}

//打开一个frame组
function hb_openframegroupby_auto(groupname, frames) {
	var hh = $('header')[0] ? $('header').offset().height : 0,
		fh = $('footer')[0] ? $('footer').offset().height : 0;
	api.openFrameGroup({
		name: groupname,
		background: '#fff',
		scrollEnabled: false,
		rect: {
			x: 0,
			y: hh,
			w: 'auto',
			h: api.winHeight - hh - fh
		},
		index: 0,
		frames: frames
	}, function (ret, err) {
		var index = ret.index;

	});
}

var emp = $api.getStorage("emp")

//ajax发送请求获取响应数据
function post_ajax(url, datas, callback) {
	var token = $api.getStorage('token');
	hds = {
		'Content-Type': 'application/json;charset=utf-8'
	};
	if (token) {
		hds.token = token;
	}
	api.showProgress({
		style: 'default',
		animationType: 'fade',
		title: '查询中...',
		text: '请稍等...',
		modal: true
	});

	api.ajax({
		headers: hds, //传送token
		url: ROOTHTTP + url,
		method: 'post',
		timeout: 10,
		data: {
			body: JSON.stringify(datas)
		},
	}, function (ret, err) {
		callback(ret, err)
		if (ret.code == 401) {
			alert("登录失效，请重新登录！")
			$api.rmStorage('emp'); //清除登录信息
			$api.rmStorage('token'); //清除token信息
			$api.rmStorage('first_login');
			sendting('tiaoToFrame0') //是mian跳到frame0

			api.openWin({
				name: 'login',
				url: 'widget://html/login.html',
				pageParam: {
					index: 1
				},
				slidBackEnabled: false,
				reload: true
			});
			return
		}
		api.hideProgress();
	});

}

//ajax发送请求获取响应数据
function get_ajax(url, datas, callback) {
	var token = $api.getStorage('token');
	hds = {};
	if (token) {
		hds.token = token;
	}

	api.showProgress({
		style: 'default',
		animationType: 'fade',
		title: '查询中...',
		text: '请稍等...',
		modal: true
	});
	if (emp) {
		var key = "token"
		var val = emp.accessToken
		datas[key] = val
	}

	api.ajax({
		headers: hds, //传送token
		url: ROOTHTTP + url,
		method: 'GET',
		timeout: 10,
		dataType: 'json',
		data: {
			values: datas
		},
		contentType: "application/json",
	}, function (ret, err) {
		callback(ret, err)
		if (ret.code == 401) {
			alert("登录失效，请重新登录！")
			$api.rmStorage('emp'); //清除登录信息
			$api.rmStorage('token'); //清除token信息
			$api.rmStorage('first_login');
			sendting('tiaoToFrame0') //是mian跳到frame0

			api.openWin({
				name: 'login',
				url: 'widget://html/login.html',
				pageParam: {
					index: 1
				},
				slidBackEnabled: false,
				reload: true
			});
		}
		api.hideProgress();
	});

}

//ajax发送请求获取响应数据——无加载框
function get_ajax_none(url, datas, callback) {
	var token = $api.getStorage('token');
	hds = {};
	if (token) {
		hds.token = token;
	}

	if (emp) {
		var key = "token"
		var val = emp.accessToken
		datas[key] = val
	}

	api.ajax({
		headers: hds, //传送token
		url: ROOTHTTP + url,
		method: 'GET',
		timeout: 10,
		dataType: 'json',
		data: {
			values: datas
		},
		contentType: "application/json",
	}, function (ret, err) {
		callback(ret, err)
		if (ret.code == 401) {
			//alert("登录失效，请重新登录！")
			$api.rmStorage('emp'); //清除登录信息
			$api.rmStorage('token'); //清除token信息
			$api.rmStorage('first_login');
			sendting('tiaoToFrame0') //是mian跳到frame0

			api.openWin({
				name: 'login',
				url: 'widget://html/login.html',
				pageParam: {
					index: 1
				},
				slidBackEnabled: false,
				reload: true
			});
		}
	});

}
//单张图片缓存方法
/**
 *
 * @param {Object} data Json数组对象
 * @param {string} tag	ID标记名
 * @param {int} tagid	数组中对象的ID名
 * @param {int} index	起始的序号
 * @param {string} param	获取图片的属性名
 */
function hb_image_cache(data, tag, tagid, index, param) {
	if (index > data.length - 1) {
		return;
	}
	//	alert(admin_ROOTIMAGE+eval('data['+index+'].'+param));
	//	alert(tag+eval('data['+index+'].'+tagid));
	//return;
	api.imageCache({
		url: admin_ROOTIMAGE + eval('data[' + index + '].' + param)
	}, function (ret, err) {
		$(tag + eval('data[' + index + '].' + tagid)).data('echo', ret.url);
		hb_image_cache(data, tag, tagid, ++index, param);
	});

	//图片加载
	Echo.init({
		offset: 0,
		throttle: 0
	});
}




function hb_homeimage_cache(data, tag, tagid, index, param) {
	if (index > data.length - 1) {
		return;
	}
	//	alert(ROOTIMAGE+eval('data['+index+'].'+param));
	//	alert(tag+eval('data['+index+'].'+tagid));
	//	return;
	api.imageCache({
		url: ROOTIMAGE + eval('data[' + index + '].' + param)
	}, function (ret, err) {
		$(tag + eval('data[' + index + '].' + tagid)).data('echo', ret.url);
		hb_homeimage_cache(data, tag, tagid, ++index, param);
	});

	//图片加载
	Echo.init({
		offset: 0,
		throttle: 0
	});
}









//清除输入框的内容
function hb_clear(obj) {
	$(obj).prev().children().val('');
}

//随机一条广告语
function hb_random_ad(tag) {
	$(tag).html(arr_pepro_ad[hb_random(0, arr_pepro_ad.length - 1)]);
}

//随机函数
function hb_random(min, max) {
	var range = max - min;
	var rand = Math.random();
	return (min + Math.round(rand * range));
}

//密码加密方式
function hb_encryption(pwd) {
	var str = 'askhoq!nfdgrut07832wr%yre834taay4kq907iu_hf';
	var len = str.length;
	var pw = '';
	//循环遍历pwd在pwd的头尾和中间随机插入str中的值
	for (var i = 0; i < pwd.length; i++) {
		pw += pwd.charAt(i);
		pw += str.charAt(hb_random(0, len));
	}
	return pw;
}


function toast(msg) {
	api.toast({
		msg: msg,
		position: 'top'
	});


}


//打开一个窗口
function openwin(tourl) {

	api.openWin({
		name: tourl,
		url: tourl + '.html',
		slidBackEnabled: false,
		animation: {
			type: 'movein',
			subType: 'from_right',
			duration: 300
		},
		slidBackEnabled: false
	});

}


//带传值的openwin

function openwin_zhi(tourl, zhi) {

	api.openWin({
		name: tourl,
		url: tourl + '.html',
		slidBackEnabled: false,
		pageParam: {
			zhi: zhi
		},
		animation: {
			type: 'movein',
			subType: 'from_right',
			duration: 300
		},
		slidBackEnabled: false

	});

}

//封装的发送监听事件
function sendting(name) {
	//alert(5555);
	api.sendEvent({
		name: name,
		extra: {}
	});


}



//封装的发送监听事件
function sendting_zhi(name, value) {
	//alert(5555);
	api.sendEvent({
		name: name,
		extra: {
			value: value
		}
	});


}


//保留两位小数
//功能：将浮点数四舍五入，取小数点后3位
function toDecimal(x, weishu) {
	var f = parseFloat(x);
	if (isNaN(f)) {
		return;
	}
	if (weishu == 1) {
		f = Math.round(x * 10) / 10;
	}
	if (weishu == 2) {
		f = Math.round(x * 100) / 100;
	}
	if (weishu == 3) {
		f = Math.round(x * 1000) / 1000;
	}


	return f;
}

//js获取当前日期
function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate;
	return currentdate;
}

//检查用户是否登录
function checkLogin() {

	if ($api.getStorage('emp')) {
		return true;
	} else {
		api.confirm({
			title: '您需要先登录哦！',
			msg: '点击确认跳到登录页面',
			buttons: ['先逛逛', '确定']
		}, function (ret, err) {
			var index = ret.buttonIndex;
			if (index == 2) { //确认跳转登录页面
				api.openWin({
					name: 'login',
					url: 'widget://html/login.html',
					slidBackEnabled: false,
					reload: true
				});
			}
		});
	}

}


//隐藏手机号的中间4位为*号
function hideTel4(tel) {

	var reg = /^(\d{3})\d{4}(\d{4})$/;
	var newtel = tel.replace(reg, "$1****$2");
	return newtel;
}


function getSuijiFilename() {
	var suijishu = Math.floor(Math.random() * 900000) + 100000
	return suijishu + new Date().getTime()
}

//获取当前年月日
function getNowDate() {
	var nowDate = new Date()
	var year = nowDate.getFullYear()
	var month = nowDate.getMonth() + 1
	var day = nowDate.getDate()
	return year + '-' + month + '-' + day
}

//二次判定是否拥有调用权限
function isJuris(perm, text) {
	var has = hasPermission(perm);
	if (!has || !has[0] || !has[0].granted) {
		api.confirm({
			title: '提醒',
			msg: "我们需要获取您的" + text + "使用权限",
			buttons: ['确定', '取消']
		}, function (ret, err) {
			if (1 == ret.buttonIndex) {
				obJuris(perm); //获取权限请求
			} else {
				return false;
			}
		});
		return false;
	}
	return true;
}
//判定是否有权限
function hasPermission(one_per) {
	var perms = new Array();
	if (one_per) {
		perms.push(one_per);
	}
	var rets = api.hasPermission({
		list: perms
	});
	return rets;
}
//获取权限
function obJuris(one_per) {
	var perms = new Array();
	if (one_per) {
		perms.push(one_per);
	}
	api.requestPermission({
		list: perms,
		code: 100001
	}, function (ret, err) {
		console.log(JSON.stringify(ret));
	});
}